Skip to content

fix(usage): report usage fetch failures correctly and keep their backoff - #813

Open
eric-engberg wants to merge 19 commits into
sirmalloc:mainfrom
eric-engberg:fix/usage-fetch-failures
Open

eric-engberg wants to merge 19 commits into
sirmalloc:mainfrom
eric-engberg:fix/usage-fetch-failures

Conversation

@eric-engberg

Copy link
Copy Markdown
Contributor

What

Five fixes to how the usage widgets behave when the usage fetch fails or its backoff can't be saved. The cache-folder fix (4) also covers Claude Status.

  1. [Timeout] after an API error. When the usage API fails with anything other than a 429 or a parse error, renders inside the 30-second backoff now show [API Error], like the render that sent the request, instead of [Timeout].
  2. A short lock dated ahead by a clock set back. A 30-second in-flight, API-error or parse-error lock, or a legacy empty lock, written while the clock ran more than 30 seconds fast no longer blocks fetching for as long as the clock was off.
  3. A connection dropped mid-body. The usage fetch settles as soon as the response stream fails, instead of holding the status line for the full five-second deadline.
  4. An unwritable ~/.cache. When ~/.cache/ccstatusline can't be created or written, the usage and Claude Status caches and backoff locks move to an owner-only ccstatusline-<uid> folder in the system temp folder. Renders then stop calling both endpoints every time, and a 429's Retry-After holds.
  5. Reset timers stuck on [Loading]. Block Reset Timer and Weekly Reset Timer now keep the [Loading] placeholder only while the data is on its way or the failure clears up on its own: the usage API answers 429 before Claude Code's payload carries rate_limits, another render's fetch is still in flight, or the fetch hits a 5xx or 408 response, a network error, or the 5-second limit. A failure that lasts shows its usage error on those lines: no OAuth login, a token the API rejects (401 or 403) or another 4xx answer, a server certificate that doesn't verify (as behind a proxy or firewall that intercepts TLS with a certificate the runtime doesn't trust), or a response that can't be read. Before, every error became [Loading], forever when the failure never cleared.

Why

Every render is a new process, so the files in ~/.cache/ccstatusline are the only state shared between renders. Each of these bugs is a way that state went wrong or went missing.

  1. Before each request, fetchUsageData writes a 30-second in-flight lock labeled timeout. A 429 and a parse error overwrite it with their own kind. Every other failure (401, 403, 5xx, a proxy refusing CONNECT, a network error) left it in place, and the lock schema had no api-error value to store anyway. With a fake API answering 401 and no usage cache yet, render 1 showed [API Error] and renders 2-4 showed [Timeout], with one request sent. Parse errors already get their own parse-error lock for exactly this reason.
  2. readActiveUsageLock honored any deadline up to 24 hours ahead, whatever kind of lock it was. Only a 429's Retry-After can legitimately run past 30 seconds. With the clock 3 hours fast and a failing fetch, then the clock corrected and the API answering again, every render showed [Timeout] and sent nothing until real time caught up. The no-credentials lock and usage.json already reject entries dated ahead like this. A legacy empty lock with a future mtime had no upper bound at all.
  3. The response handler listened only for data and end. When the connection drops after the headers, Node and Bun emit aborted and error on the response and neither error nor timeout on the request, so only the deadline settled the fetch. Through a local TLS proxy that sends the headers and half the body, then drops the connection, a render took 5.22 s under Bun and 5.28 s under Node. The Claude Status fetch already listens for both events.
  4. Every cache and lock write swallows its error. With a read-only ~/.cache (for example, one left owned by root by an earlier sudo command), nothing throttled anything. Through a local proxy that drops every connection, three renders of a Block Usage | Claude Status line made six connections, three to the usage API and three to the status page, under both runtimes. A 429 with Retry-After: 600 was ignored and the API was called again on every render. While either endpoint didn't answer, every render waited out its five-second deadline again.
  5. The [Loading] placeholder was added (aae5add) so that a 429 during Claude Code's startup, before its payload carries rate_limits, wouldn't show as [Rate limited]. Prefetch did that by dropping every fetch error on lines whose only missing data is a timer's reset time, not just the 429.
    • With no OAuth login (an API-key, Bedrock or Vertex session, or a logged-out profile) and no rate_limits in the payload, a reset-only line showed Weekly Reset: [Loading] | Reset: [Loading] on every render, forever. Adding Weekly Usage to the same layout turned all of them into [No credentials].
    • A token the API rejects showed the same [Loading] line, after one request.
    • The fetch reported a 401, a 5xx, a network error and its own 5-second deadline as the same api-error, so a rejected token couldn't be told apart from a brief outage. Showing every api-error would put [API Error] on these lines for the whole 30-second backoff of an outage that clears up by itself, so the fetch now records whether the failure clears up on its own. A 5xx, a 408 (a server or proxy that gave up waiting for the request), a network error, a response cut off mid-body and the deadline do. Any other answer refuses the request itself (a 401 or 403 for a token the API rejects, a 407 from a proxy that wants its own login, a 404, a 200 with nothing in it), and every render sends the same request, so it is refused again until the login or the setup changes. A server certificate that doesn't verify also fails every request the same way: behind a proxy or firewall that intercepts TLS with a certificate the runtime doesn't trust, nothing changes until the runtime is set up to trust it (for example with NODE_EXTRA_CA_CERTS) or the certificates change. Those show [API Error], as Weekly Usage already does on the same account. A 429 and another render's fetch in flight (whose lock reads as timeout) mean the data is on its way, so they keep [Loading] along with the failures that clear up.

How

  • usage-fetch.ts
    • New api-error lock kind. The failure path swaps this render's own in-flight record for a 30-second api-error lock (replaceOwnUsageLock). Like clearOwnUsageLock, it leaves alone a 429 lock written by a concurrent render.
    • Per-kind lock horizon (getUsageLockHorizon): 24 hours for rate limits, one minute for the other kinds and for the legacy mtime lock. That is one backoff beyond their own 30 seconds, so a concurrent render that read the clock a moment later still counts. A lock dated further ahead is ignored, and the next fetch rewrites it.
    • The response's aborted and error events settle the fetch as an error.
    • A failed request's result and its api-error lock record whether the failure clears up on its own (errorTransient on the result, "transient": true in the lock): a 5xx or 408, a network error, a response cut off mid-body, an idle socket or the deadline. Every other answer, a request error whose code says the server's certificate doesn't verify, and a proxy setting that can't be used write no marker. A lock without one, including one from before the marker existed, reads as a lasting failure. The marker stops at prefetch, so widgets that show errors still show [API Error].
    • The certificate codes (LASTING_REQUEST_ERROR_CODES) include the ten that Node and Bun report, directly and through the proxy agent's tunnel, for a self-signed certificate, one from an unknown CA (alone, with its root, or with an intermediate but not the root), one whose intermediate is trusted but not its root, one signed by a certificate that isn't a CA, an expired or not-yet-valid one and one for another host: DEPTH_ZERO_SELF_SIGNED_CERT, UNABLE_TO_VERIFY_LEAF_SIGNATURE, SELF_SIGNED_CERT_IN_CHAIN, UNABLE_TO_GET_ISSUER_CERT_LOCALLY, UNABLE_TO_GET_ISSUER_CERT, INVALID_PURPOSE, CERT_HAS_EXPIRED, CERT_NOT_YET_VALID and ERR_TLS_CERT_ALTNAME_INVALID, plus UNSPECIFIED, the runtimes' name for a verification failure with no name of its own (under Node: a CA whose key usage leaves out certificate signing, a weak leaf key, a SHA-1 signature). The set also holds the rest of the verification error names the two runtimes share (UNABLE_TO_GET_CRL, CERT_SIGNATURE_FAILURE, CERT_CHAIN_TOO_LONG, CERT_REVOKED, INVALID_CA, PATH_LENGTH_EXCEEDED, CERT_UNTRUSTED, CERT_REJECTED, HOSTNAME_MISMATCH and the CRL and date-field errors), except OUT_OF_MEM, which isn't about the certificate. See Testing. Messages aren't matched, since they differ between the runtimes.
    • A connection failure after an answer that already refused the request counts as that refusal. When a proxy refuses CONNECT, the proxy agent replays the proxy's answer as the response, and under Bun the request's connection fails before that response ends. Without this, a proxy's 407 or 403 would keep reset-only timers on [Loading] under Bun while Node shows [API Error].
  • New cache-dir.ts
    • getWritableCacheDir() is resolved once per process: ~/.cache/ccstatusline when it can be created and written, otherwise <tmp>/ccstatusline-<uid>.
    • The temp folder is shared between accounts on Linux, so the fallback is created 0700 and used only while it is a real folder (not a link) owned by this account that no other account can write to. Otherwise nothing changes from today.
    • usage-fetch.ts (usage.json, usage.lock, usage-credentials.lock) and claude-service-status.ts (claude-status.json, claude-status.lock) resolve their files through it.
  • usage-prefetch.ts: for lines whose only missing data is a timer's reset time, only rate-limited, timeout (another render's fetch in flight) and an api-error marked as clearing up on its own are still dropped.
  • Tests: the usage subprocess probes get two response-stream failure modes and an idle-socket timeout, time their first fetch, and get their own TMPDIR/TMP/TEMP, so a probe with an unwritable home can't reach the real temp folder. cache-dir.ts exposes __testing hooks, since os.homedir() can't be redirected in every runtime. A new startRefusingProxy helper counts Claude Status connections, and a new startAnsweringProxy helper answers CONNECT with a given status, so a usage request goes through the real proxy agent. A new startTunnelingProxy helper opens every CONNECT tunnel to a local server. A new tls-test-helpers.ts builds test certificates with node:crypto (no tooling, no private key checked in), including a CA whose key usage leaves out certificate signing (keyUsageWithoutCertSign), and serves them from a local TLS server, so certificate failures go through the real proxy agent and TLS stack. The probes can give their request error a code and also prefetch for reset-only lines.
  • Docs: docs/DEVELOPMENT.md (lock horizons, the api-error lock and its transient marker, the cache-folder fallback, the probe sandbox) and docs/USAGE.md (when the reset timers show the loading placeholder and when they show the usage error).
  • Left as is:
    • A rate-limit lock keeps the 24-hour horizon, since a Retry-After can legitimately run that long. One written under a clock running fast still holds until its deadline.
    • The other files in ~/.cache/ccstatusline (git, pull request, block, custom-command and terminal-width caches, skill logs) stay where they are. Losing most of them costs only local recomputation. The Git PR/MR and Git CI Status lookup through gh or glab can't write its refresh lock there, so it stops refreshing rather than running on every render.
    • A request that runs past the 5-second deadline shows [API Error], now on every render inside its backoff (reset-only lines keep [Loading]). It gets no label of its own.
    • On Windows the fallback is ccstatusline in the per-user %TEMP%, and Node's write-access check there ignores ACLs, so the fallback mainly helps on macOS and Linux.

Demo

Each demo pipes renders through the real CLI with a fake login (or none), a security stub, and a preloaded fake usage API and status page. Nothing is fetched.

1. Label inside an API failure's backoff

The usage API rejects the token, and the line renders four times a second apart. Before: [API Error], then [Timeout] three times. After: [API Error] four times. One request either way.

Powerline

Before:

Usage API failure, before, Powerline

After:

Usage API failure, after, Powerline

Plain

Before:

Usage API failure, before, plain

After:

Usage API failure, after, plain

2. Clock set back after a failed fetch

The clock runs 3 hours fast while a fetch fails, then is set back while the API answers again. Before: [Timeout] and no request sent (1 in total). After: 5h: 42.0% / Weekly: 17.0% at once (2 requests in total).

Powerline

Before:

Clock set back, before, Powerline

After:

Clock set back, after, Powerline

Plain

Before:

Clock set back, before, plain

After:

Clock set back, after, plain

3. Connection dropped mid-body

One render with a complete answer and one with the connection dropping after the headers, each timed. Before: the dropped render takes 5.2-5.3 s. After: 0.3 s.

Powerline

Before:

Dropped response, before, Powerline

After:

Dropped response, after, Powerline

Plain

Before:

Dropped response, before, plain

After:

Dropped response, after, plain

4. Read-only ~/.cache

Three renders with a 429 (Retry-After: 600) from the usage API and an unreachable status page, counting the requests sent. Before: 3 usage API and 3 status page requests. After: 1 and 1.

Powerline

Before:

Read-only cache, before, Powerline

After:

Read-only cache, after, Powerline

Plain

Before:

Read-only cache, before, plain

After:

Read-only cache, after, plain

5. Reset timers with no login or a rejected token

Weekly Reset Timer and Block Reset Timer with no rate_limits in the payload, two renders each. Before: Weekly Reset: [Loading] | Reset: [Loading] every time. After: [No credentials] with no login, [API Error] with a rejected token. A 5xx, a 408 or a network error keeps [Loading] both before and after, so it has no demo of its own. A server certificate that doesn't verify changes like a rejected token, from [Loading] to [API Error].

Powerline

Before:

Reset timers, before, Powerline

After:

Reset timers, after, Powerline

Plain

Before:

Reset timers, before, plain

After:

Reset timers, after, plain

Testing

  • On main as of 2.2.34 (0c94df7): it merges after conflicts next to feat: add an Extra Usage Today widget #811's profile request, resolved by keeping both: usage-account.json moves to the writable cache folder like the other usage files, and a profile request that throws counts as a lasting failure. bun run lint is clean, and bun test on Linux CI gives 4479 pass, 0 fail (4403 on main). The built CLI under Bun 1.4.4 and Node 26.13.0 agrees across runtimes and matches main in plain and Powerline mode, and the TUI opens and exits cleanly under both. It adds no JavaScript or Node API newer than Node 14, the build's target.

  • 76 new tests and one new test file:

    • cache-dir.test.ts (5, new file): the preferred folder, the fallback and its reuse, and passing over a fallback that other accounts can write to or that is a link.
    • usage-fetch.test.ts (64), usage-prefetch.test.ts (6), claude-service-status.test.ts (1).
  • The 71 new tests outside cache-dir.test.ts, run against main's source (keeping the new cache-dir.ts so the test files load): 66 fail.

    • the api-error lock label (1)
    • short locks dated ahead: the timeout and parse-error kinds and the legacy mtime lock (3)
    • a response stream that fails mid-body (2; each waits out the full 5 s on main)
    • the backoff holding with a read-only ~/.cache, for a 429 and an API error (2)
    • the Claude Status lock landing in the writable cache folder (1)
    • reset-only prefetch keeping no-credentials, api-error and parse-error (3)
    • the transient marker on a 503, a 408, a network error (no code, ECONNREFUSED, ECONNRESET or ENOTFOUND) and an idle-socket timeout, on the failed render and inside its backoff, with a reset-only line's prefetch dropping it (7)
    • a 403, a 404, a proxy's 407 and an empty 200 staying a lasting api-error inside the backoff (4; main's backoff renders read timeout)
    • a concurrent render's 429 lock surviving a failed fetch (1; its result now carries the transient marker, which main doesn't write. It still guards the 429 lock and fails when the lock is replaced unconditionally)
    • a local proxy's 407, 403, 502 and 408 answer to CONNECT, through the real proxy agent: lasting, lasting, transient and transient (4; main's fetch result carries no marker)
    • a request error carrying each of the 29 certificate verification codes staying a lasting api-error with no lock marker, on the failed render and inside its backoff, with a reset-only line's prefetch keeping it (29)
    • through a local proxy's tunnel, a local TLS server presenting a self-signed certificate, one from an unknown CA (alone, with its root, or with only an intermediate), one signed by an issuer that isn't a CA, one signed by a CA whose key usage leaves out certificate signing, an expired one and one not valid yet, each a lasting error, and a connection dropped before the TLS handshake ends, a transient one (9; main's fetch result carries no marker)
  • Two existing tests also fail on main, because their expectations change. In the root-errors walkthrough, a non-429 failure's lock and the renders inside it now read api-error, not timeout, and the network error's result and lock carry the transient marker. One of its steps rendered 181 s before the render whose lock it relied on (a clock set back), so it now renders inside that lock's backoff. The stalled-proxy deadline test now expects the fetch to report its failure as transient.

  • The other 5 pass on main:

    • The api-error short-lock case passes there for a different reason. main's lock schema has no api-error, so it rejects the JSON lock, falls back to the file's mtime, which is long past the test's clock, and fetches anyway. It still guards this branch, where api-error locks are valid and the 24-hour horizon would honor one dated 3 hours ahead. It fails against the code of this branch's first commit, which adds the api-error lock but not the per-kind horizon.
    • Two guards, each confirmed to fail when its case is broken on purpose:
      • an in-flight lock dated a second ahead is still honored (fails with a strict 30-second horizon)
      • another render's in-flight fetch still leaves a reset-only line on its loading placeholder (fails when timeout is dropped from the transient errors)
    • A transient api-error leaving a reset-only line on its loading placeholder: main drops every error there. It fails against this branch's fifth commit, which shows every api-error.
    • A transient api-error still reaching a line that shows errors, as a plain api-error: a guard that fails when the error is dropped for every line, or when the marker is passed on to the widgets.
  • Run commit by commit, each commit's tests against its parent's source: in the first five commits, the same 12 new tests and the changed existing test fail, and so does the api-error short-lock case, while the two guards above and the concurrent-429 test pass. Against the fifth commit's source, 10 of the sixth commit's tests fail: the transient marker (3), the reset-only prefetch of a transient api-error (1), and six tests whose expectations gained the marker (the root-errors walkthrough, the deadline test, the concurrent-429 test, the read-only-cache api-error backoff, and the two mid-body drops). Its five guards pass: the four lasting api-error cases, each failing when every api-error is marked transient, and the prefetch guard above. Against the sixth commit's source, the seventh commit's proxy 407 and 403 tests fail under Bun, where that source marked both transient. Its 502 test passes there, and fails when every failure after an answer counts as a refusal. Under Node vitest, all three pass against the sixth commit's source. Against the seventh commit's source, under Bun, the eighth commit's 13 certificate tests fail (7 stubbed codes, 6 real certificates through the tunnel); the 6 tunnel tests also fail under Node vitest. Its 4 guards pass: a refused connection, a reset connection and a failed DNS lookup staying transient, and a connection dropped before the TLS handshake ends. Each fails when every request error counts as lasting. Against the eighth commit's source, the ninth commit's 2 tests fail: a 408 from the API, and a proxy's 408 for CONNECT (also under Node vitest). Against the ninth commit's source, under Bun, 4 of the tenth commit's 5 tests fail: the three new stubbed codes and the issuer that isn't a CA through the tunnel. Its CA without certificate signing passes there, because Bun reports it as UNABLE_TO_VERIFY_LEAF_SIGNATURE. Under Node vitest, where the probes don't load, both of its tunnel tests fail.

  • Node 26.10.0 vitest on the 4 changed test files: 126 pass, 92 fail of 218. main, on the 3 of them it has: 101 pass, 41 fail of 142.

    • cache-dir, claude-service-status and usage-prefetch pass fully.
    • Every failure in both trees is in usage-fetch: the subprocess probes stop with ERR_MODULE_NOT_FOUND under Node vitest (41 of 64 on main, 92 of 128 here). The 51 new probe tests there fail the same way, and the 13 new in-process tests pass (4 proxy CONNECT answers, 8 certificate chains through a tunnel, a connection dropped mid-handshake). The other 23 pass in both.
  • Certificate failures, observed with local TLS servers and openssl-made certificates. Each was reached directly and through the proxy agent's CONNECT tunnel, with the same code both ways ("trusted CA" = test root in NODE_EXTRA_CA_CERTS):

    Server certificate Bun 1.4.2 Node 26.10.0
    self-signed DEPTH_ZERO_SELF_SIGNED_CERT DEPTH_ZERO_SELF_SIGNED_CERT
    unknown CA, leaf only UNABLE_TO_VERIFY_LEAF_SIGNATURE UNABLE_TO_VERIFY_LEAF_SIGNATURE
    unknown CA, with its root SELF_SIGNED_CERT_IN_CHAIN SELF_SIGNED_CERT_IN_CHAIN
    unknown CA, intermediate only UNABLE_TO_GET_ISSUER_CERT_LOCALLY UNABLE_TO_GET_ISSUER_CERT_LOCALLY
    unknown root, intermediate trusted (sent or not) UNABLE_TO_GET_ISSUER_CERT UNABLE_TO_GET_ISSUER_CERT
    expired, unknown CA UNABLE_TO_VERIFY_LEAF_SIGNATURE CERT_HAS_EXPIRED
    expired, trusted CA CERT_HAS_EXPIRED CERT_HAS_EXPIRED
    not yet valid, unknown CA UNABLE_TO_VERIFY_LEAF_SIGNATURE CERT_NOT_YET_VALID
    not yet valid, trusted CA CERT_NOT_YET_VALID CERT_NOT_YET_VALID
    other host, unknown CA UNABLE_TO_VERIFY_LEAF_SIGNATURE UNABLE_TO_VERIFY_LEAF_SIGNATURE
    other host, trusted CA ERR_TLS_CERT_ALTNAME_INVALID ERR_TLS_CERT_ALTNAME_INVALID
    issuer not a CA, CA trusted or not INVALID_PURPOSE INVALID_PURPOSE
    issuing CA without certificate signing, CA trusted or not UNABLE_TO_VERIFY_LEAF_SIGNATURE UNSPECIFIED
    SHA-1 signature, trusted CA (accepted) UNSPECIFIED
    RSA-1024 leaf key, trusted CA (accepted) UNSPECIFIED
    nothing listening ECONNREFUSED ECONNREFUSED
    connection reset ECONNRESET ECONNRESET

    Messages differ: Node 26 appends a --use-system-ca hint. The test-built certificates give the same codes per runtime. Other Node versions were not checked.

  • Built CLI under Bun 1.4.2 and Node 26.10.0 (rerun at the tenth commit: unchanged): the baseline plain and Powerline renders match across runtimes and match main, and the TUI opens and exits cleanly. A Weekly Reset Timer | Block Reset Timer line with no rate_limits renders the same under both runtimes. With no login it differs from main as intended. With a fake login and a proxy that refuses connections it matches main ([Loading] on a fresh fetch and inside the backoff, whose lock is marked transient).

  • Manual renders, main vs this branch (Bun from source, Node from the built CLI):

    • a mid-body drop through a local TLS proxy: 5.22 s (Bun) and 5.28 s (Node) before, 0.33 s and 0.40 s after
    • a read-only ~/.cache with every connection dropped: 6 connections over 3 renders before, 2 after (one usage API, one status page), under both runtimes. The files land in ccstatusline-<uid> in the temp folder, and ~/.cache stays empty.
    • a reset-only line with no rate_limits, two renders each with the second inside the first's backoff (Bun): no login, [Loading] before and [No credentials] after; a stubbed 401 or 403, [Loading] before and [API Error] after; a stubbed 503, a network error, an idle-socket timeout or the 5-second deadline, [Loading] on both; a 429, [Loading] on both. One request per pair with a login.
    • a reset-only line behind a local proxy that answers CONNECT with 407, 403 or 502, Bun from source and the Node bundle: [Loading] before for all three; [API Error] after for 407 and 403, [Loading] for 502
    • the same line behind a proxy that answers CONNECT with 408: [Loading] before and after under both runtimes, with the lock marked transient after
    • a reset-only line behind a local proxy whose tunnel leads to a local TLS server, Bun from source and the Node bundle, two renders each: a self-signed certificate, an unknown CA's intermediate without its root, and, with the test CA trusted through NODE_EXTRA_CA_CERTS, an expired certificate and one for another host. Before: [Loading]. After: [API Error], with no transient marker in the lock. A valid certificate from the trusted CA shows the reset times on both; nothing listening keeps [Loading] on both. One CONNECT per pair.
    • the same line with only the intermediate trusted (sent by the server or not), an issuer that isn't a CA, or a CA without certificate signing (the last two with the CA trusted and without): [Loading] before, [API Error] with no marker after, under both runtimes. With the CA trusted, a SHA-1 signature and an RSA-1024 leaf key change the same way under Node; Bun accepts both and shows the reset times before and after. One CONNECT per pair.
    • a Weekly Usage | Block Reset Timer line with a stubbed 503 or network error: [API Error] on both renders, where main shows [Timeout] on the second

Before each request, fetchUsageData writes a 30-second in-flight lock
labeled 'timeout'. A 429 and a parse error overwrite it with their own
kind, but any other failure (a 401 or 5xx, a proxy refusing CONNECT, a
network error) left it in place, and the lock schema had no 'api-error'
value to store anyway. Each render is a new process, so only the render
that made the request showed [API Error]; every other render for the
next 30 seconds read the lock and showed [Timeout] about a server that
had answered at once.

The failure path now swaps the in-flight record for a 30-second
'api-error' lock, so renders inside the backoff show [API Error] too.
Like clearing the lock after a success, it only replaces the record
this process wrote, so a 429 lock written by a concurrent render keeps
its Retry-After window.
The usage lock stores an absolute deadline, and readActiveUsageLock
honored any deadline up to 24 hours ahead, whatever kind of lock it
was. Only a 429's Retry-After can legitimately run that far; the
in-flight, API-error and parse-error locks are always written 30
seconds ahead. So when such a lock was written while the system clock
ran hours fast (a fetch that failed or was cancelled just before NTP or
a manual change set the clock back), every render skipped the fetch
for as long as the clock had been fast, showing [Timeout] or the
frozen pre-correction numbers. A legacy empty lock with a future mtime
had no upper bound at all.

Each kind of lock now has its own horizon: 24 hours for rate limits,
and for the rest one backoff beyond their own 30 seconds, which still
covers a concurrent render that read the clock a moment later. A lock
dated further ahead is ignored and the next fetch rewrites it, as the
no-credentials lock and usage.json already handle a clock set back.

One test step rendered 181 seconds before the render whose lock it
relied on, so it now renders inside that lock's backoff instead.
fetchFromUsageApi listened only for the response's 'data' and 'end'.
When the connection drops after the headers but before the body is
complete (a reset from a proxy or the server, a VPN reconnect), Node
and Bun emit 'aborted' and 'error' on the response, never 'end', and
no 'error' on the request; the idle timeout can't fire on a socket
that is already closed. Only the five-second deadline settled the
fetch, so the whole status line waited about 5 s before showing
[API Error]. Through a local proxy that cuts the body short, a render
took 5.2-5.4 s under both runtimes.

The response now settles the fetch as an error on 'aborted' or
'error', as the Claude Status fetch already does. The same render
takes about 0.3 s.
Every render is a new process, so the usage and Claude Status fetches
are throttled only by files in ~/.cache/ccstatusline: the in-flight
and Retry-After locks, the no-credentials lock, usage.json, and the
status page's cache and failure lock. Every write swallows its error,
so when that folder can't be created or written (a ~/.cache left owned
by root by an earlier sudo command, a read-only home) nothing throttled
anything. Each render called the usage API and the status page again,
a 429's Retry-After was never saved, and while either endpoint was
unreachable every render waited out its five-second deadline. With a
read-only ~/.cache, three renders made six connections instead of two.

Both modules now keep these files in one folder resolved once per
process: ~/.cache/ccstatusline when it can be created and written,
otherwise ccstatusline-<uid> in the system temp folder. That folder is
shared between accounts on Linux, so the fallback is created
owner-only and used only while it is a real folder this account owns
that no other account can write to; otherwise the files stay where
they were, as before.

The usage probes now also get their own temp folder, so a probe with
an unwritable home can't reach the real one.
Block Reset Timer and Weekly Reset Timer show [Loading] while reset
data is still arriving at startup instead of a transient API error.
Prefetch did that by dropping the fetch error whenever the only data
missing was a timer's reset time, but it dropped every kind of error,
including the ones that never clear up: no OAuth login (an API-key,
Bedrock or Vertex user, a logged-out profile), a token the API
rejects, or a response it can't parse. With no rate_limits in the
payload, those lines showed [Loading] on every render, forever, while
adding Weekly Usage to the same layout turned all of them into
[No credentials].

Only the two errors that mean the data is on its way are dropped now:
a 429 during startup, before Claude Code's payload carries rate_limits,
and another render's fetch still in flight. Any other error reaches the
timers, which already show it, or hide it with the no-data option, when
they have no reset time.
On reset-only lines (no rate_limits in Claude Code's payload), Block
Reset Timer and Weekly Reset Timer show the usage error for every fetch
failure except a 429 and another render's fetch in flight. The fetch
reports a 401, a 5xx, a network error and its own 5-second deadline all
as api-error, so a brief outage put [API Error] on those lines for the
whole 30-second backoff, where they used to keep [Loading].

The fetch now records whether an api-error clears up on its own, in its
result (errorTransient) and in the backoff lock ("transient": true), so
renders inside the backoff keep the distinction. A 5xx, a network error,
a response cut off mid-body and a request past its deadline count as
transient, and prefetch drops them on reset-only lines as it drops a
429, so the timers keep [Loading].

Any other answer refuses the request itself: a 401 or 403 for a token
the API rejects, a 407 from a proxy that wants its own login, another
4xx, or a 200 with nothing in it. Every render sends the same request,
so it would be refused again until the login or the setup changes.
Those keep showing [API Error], as do a missing login, a response that
can't be parsed and a proxy setting that can't be used.

Widgets that show usage errors still show [API Error] for every
api-error, inside the backoff too, since the marker never reaches them.
A lock without the marker, including one written before it existed,
reads as a lasting failure.
When a proxy refuses CONNECT, the proxy agent replays the proxy's answer
to the request as its response. Under Node that response ends normally
and its status decides: a 407 (the proxy wants its own login) or a 403
(it won't tunnel to the API) is a lasting API error, a 502 a transient
one. Under Bun the request's connection also fails, after the response
arrives but before it ends, and that failure settled the fetch first as
transient. Reset-only timer lines then stayed on [Loading] behind such a
proxy, with a request every 30 seconds, until its setup changed, where
Node shows [API Error].

A failure after an answer that refused the request now counts as that
refusal, so it stays lasting. A failure with no answer yet, after a 200
whose body was cut off, after a 429, or after a 5xx stays transient as
before.

The new tests answer CONNECT from a local proxy with 407, 403 and 502,
so the request goes through the proxy agent; a stubbed https.request
never takes that path.
…g error

A request whose TLS handshake fails because the server's certificate
doesn't verify counted as a network error that clears up on its own.
Behind a proxy or firewall that intercepts TLS with a certificate the
runtime doesn't trust, every request fails the same way until the
runtime is set up to trust it (for example with NODE_EXTRA_CA_CERTS),
so reset-only Block Reset Timer and Weekly Reset Timer lines kept
[Loading] for as long as that lasted, with a request every 30 seconds.
They now show [API Error], as Weekly Usage already does, and the
api-error lock carries no transient marker.

The request error's code decides. Local TLS servers with certificates
made by openssl, each reached directly and through the proxy agent's
CONNECT tunnel, gave the same code both ways:

  server certificate              Bun 1.4.2                          Node 26.10.0
  self-signed                     DEPTH_ZERO_SELF_SIGNED_CERT        DEPTH_ZERO_SELF_SIGNED_CERT
  unknown CA, leaf only           UNABLE_TO_VERIFY_LEAF_SIGNATURE    UNABLE_TO_VERIFY_LEAF_SIGNATURE
  unknown CA, with its root       SELF_SIGNED_CERT_IN_CHAIN          SELF_SIGNED_CERT_IN_CHAIN
  unknown CA, intermediate only   UNABLE_TO_GET_ISSUER_CERT_LOCALLY  UNABLE_TO_GET_ISSUER_CERT_LOCALLY
  expired, unknown CA             UNABLE_TO_VERIFY_LEAF_SIGNATURE    CERT_HAS_EXPIRED
  expired, trusted CA             CERT_HAS_EXPIRED                   CERT_HAS_EXPIRED
  not yet valid, unknown CA       UNABLE_TO_VERIFY_LEAF_SIGNATURE    CERT_NOT_YET_VALID
  not yet valid, trusted CA       CERT_NOT_YET_VALID                 CERT_NOT_YET_VALID
  other host, unknown CA          UNABLE_TO_VERIFY_LEAF_SIGNATURE    UNABLE_TO_VERIFY_LEAF_SIGNATURE
  other host, trusted CA          ERR_TLS_CERT_ALTNAME_INVALID       ERR_TLS_CERT_ALTNAME_INVALID
  (nothing listening)             ECONNREFUSED                       ECONNREFUSED
  (connection reset)              ECONNRESET                         ECONNRESET

The trusted CA came from NODE_EXTRA_CA_CERTS. Both runtimes give every
certificate failure a code, so the lasting set is those seven codes and
nothing matches on messages, which differ between the runtimes (Node 26
appends a --use-system-ca hint). Every other request error, ECONNREFUSED,
ECONNRESET and ENOTFOUND among them, still clears up on its own.

The new tests send the request through a local proxy's tunnel to a
local TLS server presenting each kind of certificate the runtime can
meet without a trusted test CA. The certificates are built in the test
with node:crypto, so no tooling or private key is needed. A stubbed
request error carrying each of the seven codes covers the result, the
lock and the reset-only prefetch, on the failed render and inside its
backoff.
A 408 Request Timeout is a server, or a proxy answering CONNECT, that
gave up waiting for the request. Unlike the other 4xx answers it says
nothing about the request itself, and a later try may well get through
in time, as after a 5xx. It counted as a refusal, so reset-only Block
Reset Timer and Weekly Reset Timer lines showed [API Error] for the
30-second backoff of a hiccup. It is now transient like a 5xx: the
result and the api-error lock carry the marker, and those lines keep
[Loading] on the failed render and inside its backoff. Every other 4xx
except 429 stays a lasting failure.

A proxy's 408 for CONNECT takes the same path, through the response the
proxy agent replays and, under Bun, the request failure that follows it.
Three kinds of server certificate that doesn't verify still counted as
a network error that clears up on its own, so behind a proxy or
firewall that intercepts TLS, reset-only Block Reset Timer and Weekly
Reset Timer lines kept [Loading], with a request every 30 seconds:

- NODE_EXTRA_CA_CERTS pointing at the interceptor's issuing
  (intermediate) CA rather than its root. Both runtimes report
  UNABLE_TO_GET_ISSUER_CERT, without the _LOCALLY suffix they give a
  chain to a root nothing trusts.
- An issuing certificate that isn't marked as a CA, which both
  runtimes report as INVALID_PURPOSE.
- Under Node, an issuing CA whose key usage leaves out signing
  certificates, a leaf key that's too weak, or a SHA-1 signature, all
  reported as UNSPECIFIED. Bun reports the first as an unknown CA, a
  code already in the set, and accepts the other two.

Each fails every request the same way until the trust store or the
certificates change. They now show [API Error], and the api-error
lock carries no transient marker.

Local TLS servers, each reached directly and through the proxy agent's
CONNECT tunnel, gave the same code both ways:

  server certificate                       Bun 1.4.2                        Node 26.10.0
  unknown root, intermediate trusted       UNABLE_TO_GET_ISSUER_CERT        UNABLE_TO_GET_ISSUER_CERT
  issuer not a CA                          INVALID_PURPOSE                  INVALID_PURPOSE
  issuing CA without certificate signing   UNABLE_TO_VERIFY_LEAF_SIGNATURE  UNSPECIFIED
  SHA-1 signature, trusted root            (accepted)                       UNSPECIFIED
  RSA-1024 leaf key, trusted root          (accepted)                       UNSPECIFIED

The intermediate came from NODE_EXTRA_CA_CERTS, with the server
sending it or not. The issuer that isn't a CA and the CA without
certificate signing gave the same code with the root trusted and
without. UNSPECIFIED is the last entry of the verify-error name table
both runtimes carry, the name for a verification failure that has none
of its own, and neither runtime uses it for anything else, so no
network failure becomes lasting through it. The lasting set is now ten
codes.

A stubbed request error with each new code covers the result, the lock
and the reset-only prefetch, on the failed render and inside its
backoff. Two more tunnel tests present a chain through an issuer that
isn't a CA and one through a CA whose key usage leaves out certificate
signing, so the test certificate helper can now build such a CA. Node
reads NODE_EXTRA_CA_CERTS only at startup, so no test in this process
can trust an intermediate, and the stub alone covers
UNABLE_TO_GET_ISSUER_CERT.
The lasting set held the verification codes seen in practice. Node and
Bun share one table of names for certificate verification failures
(UNABLE_TO_GET_CRL, CERT_SIGNATURE_FAILURE, CERT_CHAIN_TOO_LONG,
CERT_REVOKED, INVALID_CA, PATH_LENGTH_EXCEEDED, CERT_UNTRUSTED,
CERT_REJECTED, HOSTNAME_MISMATCH and the CRL and date-field errors), and
any of them fails every request the same way until the certificate or
the trust setup changes. A failure under one of those names would still
have kept the reset timers loading and retrying every 30 seconds.

Add the rest of the table, except OUT_OF_MEM, which isn't about the
certificate.
Main's stale-cache check from sirmalloc#697 (hasUsageCacheOutlivedRefresh) reads
the usage cache through getCacheFile(), this branch's cache-dir
fallback. A usage error's errorTransient and sirmalloc#697's apiSessionUsage are
both left out of UsageDataField, and each side's prefetch tests stay.
Upstream sirmalloc#266 names the usage cache and lock files per Claude config
directory; they now live in this branch's writable cache folder. Upstream
sirmalloc#724's account email cache and backoff go there too, so its backoff also
holds when ~/.cache can't be written. Tests from either side now expect
the other's file names and failure labels (sirmalloc#699's failed fetch carries
errorTransient, as fork #146 did).
# Conflicts:
#	src/utils/__tests__/claude-service-status.test.ts
#	src/utils/claude-service-status.ts
# Conflicts:
#	src/utils/claude-service-status.ts
# Conflicts:
#	docs/USAGE.md
#	src/utils/__tests__/claude-service-status.test.ts
#	src/utils/__tests__/proxy-test-helpers.ts
#	src/utils/__tests__/usage-fetch.test.ts
#	src/utils/usage-fetch.ts
#	src/utils/usage-types.ts
The build targets Node 14, which can't parse logical assignment.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant